package com.jamy.song.utils;

import com.alibaba.druid.pool.DruidDataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtil {

    private static final ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
    private static Properties prop = new Properties();
    private static DruidDataSource dataSource = new DruidDataSource();

    private static Connection conn = null;

    static {
        //数据库连接初始化
        try{
            prop.load(JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
        }catch(IOException e){
            System.out.println("数据库参数文件读取错误");
            e.printStackTrace();
        }

        dataSource.setUsername(prop.getProperty("jdbc.username"));
        dataSource.setUrl(prop.getProperty("jdbc.url"));
        dataSource.setPassword(prop.getProperty("jdbc.password"));

        try{
            dataSource.setDriverClassName(prop.getProperty("jdbc.driverClass"));
        }catch(Exception e){
            System.out.println("连接池构造异常1!");
            e.printStackTrace();
        }

        dataSource.setInitialSize(Integer.valueOf(prop.getProperty("jdbc.initialSize")));
        dataSource.setMinIdle(Integer.valueOf(prop.getProperty("jdbc.minPoolSize")));
        dataSource.setMaxActive(Integer.valueOf(prop.getProperty("jdbc.maxPoolSize")));
        dataSource.setMaxWait(Integer.valueOf(prop.getProperty("jdbc.maxWait")));
        dataSource.setTimeBetweenEvictionRunsMillis(Integer.valueOf(prop.getProperty("jdbc.timeBetweenEvictionRunsMillis")));
        dataSource.setMinEvictableIdleTimeMillis(Integer.valueOf(prop.getProperty("jdbc.minEvictableIdleTimeMillis")));
        dataSource.setValidationQuery(prop.getProperty("jdbc.query"));

        try {
            threadLocal.set(dataSource.getConnection());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    //获取连接
    public static Connection getConn(){
        conn = threadLocal.get();
        System.out.println("threadLocal获取连接:" + conn);

        try{
            if (conn == null || conn.isClosed()) {
                Class.forName(prop.getProperty("jdbc.driverClass")).toString();
                conn = DriverManager.getConnection(prop.getProperty("jdbc.url").toString(),
                                                   prop.getProperty("jdbc.username").toString(),
                                                   prop.getProperty("jdbc.password").toString());
                try{
                    dataSource.setDriverClassName(prop.getProperty("jdbc.driverClass"));
                }catch(Exception e){
                    System.out.println("连接池构造异常2!");
                    e.printStackTrace();
                    throw new IllegalStateException();
                }
            }
            System.out.println("conn:"+conn);
        }catch(Exception e){
            System.out.println("获取数据库连接异常!");
            e.printStackTrace();
            throw new IllegalStateException();
        }
        return conn;
    }


    //关闭连接
    public static void closeConn(){
        try{
            if(threadLocal.get() != null && !threadLocal.get().isClosed()){
                threadLocal.get().close();
                threadLocal.remove();
            }
        }catch(Exception e){
            System.out.println("关闭数据库连接异常!");
        }
    }



    //事务开始
    public static void beginTransaction(){
        try{
            getConn().setAutoCommit(false);
        }catch(SQLException e){
            System.out.println("开始事务异常");
            throw new IllegalStateException();
        }
    }

    //事务提交
    public static void commit(){
        try{
            getConn().commit();
        }catch(SQLException e){
            System.out.println("提交事务异常");
            throw new IllegalStateException();
        }
    }

    //事务回滚
    public static void rollback(){
        try{
            Connection conn = getConn();
            conn.setAutoCommit(false);
            conn.rollback();
            conn.setAutoCommit(true);
        }catch(SQLException e){
            System.out.println("事务回滚异常");
            throw new IllegalStateException();
        }
    }




}
